// <copyright file="CategoryRepository.cs" company="EnterpriseApi">
// Copyright (c) EnterpriseApi. All rights reserved.
// </copyright>

using EnterpriseApi.Data;
using EnterpriseApi.Models;
using Microsoft.EntityFrameworkCore;

namespace EnterpriseApi.Repositories;

/// <summary>
/// 类别仓储实现类，提供类别特有的数据访问操作
/// </summary>
public class CategoryRepository : Repository<Category>, ICategoryRepository
{
    private readonly AppDbContext _context;

    /// <summary>
    /// 初始化CategoryRepository的新实例
    /// </summary>
    /// <param name="context">数据库上下文</param>
    public CategoryRepository(AppDbContext context) : base(context)
    {
        _context = context;
    }

    /// <summary>
    /// 根据类别名称获取类别
    /// </summary>
    /// <param name="name">类别名称</param>
    /// <returns>类别对象，如果不存在则返回null</returns>
    public async Task<Category?> GetByNameAsync(string name)
    {
        return await _context.Categories.FirstOrDefaultAsync(c => c.Name == name);
    }

    /// <summary>
    /// 检查类别名称是否已存在
    /// </summary>
    /// <param name="name">类别名称</param>
    /// <returns>类别名称是否已存在</returns>
    public async Task<bool> IsNameExistsAsync(string name)
    {
        return await _context.Categories.AnyAsync(c => c.Name == name);
    }
}